const dayjs = require('dayjs')
const execa = require('execa')

async function getInfoByCommitId(commitId) {
  const splitChar = '__'
  const res = await execa('git', ['show', `--pretty=%ae${splitChar}%cd${splitChar}%H`, commitId], { stdio: 'pipe' })
  const match = res.stdout.match(/^(.*?)$/m)
  const [email, date, intactHash] = match[1].split(splitChar)
  return { email, date: dayjs(date).format('YYYY-MM-DD'), intactHash }
}
async function getSlardarReleaseLine(changeset) {
  const { email, intactHash } = await getInfoByCommitId(changeset.commit)
  const date = dayjs().format('YYYY-MM-DD')
  // - [c0b7864a4] @chenjinhuo - 2023.03.12:新增某某字段
  return `- [${changeset.commit}](https://code.byted.org/appmonitor/slardar_sdk/commit/${intactHash}) @${email} - ${date} => ${changeset.summary}`
}

async function getReleaseLine(changeset) {
  return await getSlardarReleaseLine(changeset)
}

async function getDependencyReleaseLine(_changesets, _dependenciesUpdated, _changelogOpts) {
  // self changelog has generated by getReleaseLine
  if (!_changesets.length) return ''

  const releaseLines = []
  for (const changeset of _changesets) {
    const releaseLine = await getSlardarReleaseLine(changeset)
    releaseLines.push(releaseLine)
  }
  const dependenciesUpdated = _dependenciesUpdated[0]
  const updatedBy = `- Updated By ${dependenciesUpdated.name}: ${dependenciesUpdated.oldVersion}->${dependenciesUpdated.newVersion}`
  return updatedBy + '\n' + releaseLines.map((v) => `  ${v}`).join('\n')
}

module.exports = {
  getReleaseLine,
  getDependencyReleaseLine,
}
